# -*- coding: utf-8 -*-
# standard
import os
import sys

# third
import httpx
from fastapi import APIRouter
from fastapi import Query as QueryParam
from fastapi import Header
from fastapi import Request
from fastapi import Depends
from fastapi.exceptions import HTTPException

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from toolbox.common_tools import logger
from toolbox.common_tools import INCLUDE_SCHEMA
from functions import *


"""
@Title:  从第三方平台采集数据的视图 
@File: collect_view.py
@Author: walle 2024年11日09日 09时46分39秒
@Version: 1.0.0
@Desc: 
"""


router = APIRouter()
VIEW_ARGS = dict(
    tags=['第三方平台数据采集'], 
    response_model=Resp, include_in_schema=INCLUDE_SCHEMA
)


async def check_instruction_authorization(request: Request, authorization: str | None = Header(None, description="请求头")) -> Optional[str]:
    """
    检查微服务发送get请求时授权 失败会抛出异常，否则会返回请求头或者None(没有请求头的情况)
    注意，这个函数在不同的视图的实现不同
    :return: _description_
    """
    if authorization != INSTRUCTION_AUTHORIZATION and request.url.hostname != "127.0.0.1":
        raise HTTPException(status_code=404)
    return authorization


@router.get("/collect_now", summary="立即采集数据", **VIEW_ARGS)
async def collect_now_view(
    num: int = QueryParam(0),
    authorization: str | None = Depends(check_instruction_authorization),
):  
    b = datetime.now()
    resp = await collect_third_party_platform_data()
    e = datetime.now()
    d = (e - b).total_seconds() * 1000
    resp.data = f"{num}: begin: {b}, end: {e}, 耗时：{d}毫秒"
    logger.debug(resp.data)
    return resp



if __name__ == '__main__':
    pass